/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package nwsimplex.graph;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;

/**
     * An class which can be used to traverse all vertices within a subtree in
     * bfs order. This Iterator can be reset by defining a new root vertex.
     */
    public class TreeIterator implements Iterator<Vertex>
    {

        Vertex next;
        Queue<Vertex> queue;

        /**
         * Instantiates a new TreeIterator from the root of a subtree
         *
         * @param root the root vertex of the subtree.
         */
        public TreeIterator(Vertex root)
        {
            this.next = root;
            this.queue = new LinkedList<Vertex>();

            if (next.child != null)
                queue.add(next.child);
        }

        /**
         * Sets the root of the subtree. this method can be used to reset this
         * iterator.
         *
         * @param root the new root vertex of the subtree.
         */
        public void setRoot(Vertex root)
        {
            this.next = root;
            queue.clear();

            if (next.child != null)
                queue.add(next.child);
        }

        @Override
        public boolean hasNext()
        {
            return next != null;
        }

        @Override
        public Vertex next()
        {
            Vertex result = next;

            next = queue.poll();
            if (next != null)
            {
                if (next.child != null)
                    queue.add(next.child);

                Vertex neigh = next;
                while ((neigh = neigh.rightSibbling) != null)
                    queue.add(neigh);
            }

            return result;
        }

        /*
         * Not supported.
         */
        @Override
        public void remove()
        {
            throw new UnsupportedOperationException("Not supported.");
        }

    }